package com.szrt.dapartment.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.szrt.dapartment.enity.DepartmentEntity;
import com.szrt.dapartment.service.DepartmentService;
import com.szrt.dapartment.service.impl.DepartmentServiceImpl;
import com.szrt.util.URIUtil;

public class DepartmentController extends HttpServlet {

	
	private static final long serialVersionUID = 1L;
	
	private DepartmentService service = new DepartmentServiceImpl();
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		//前台传来的是字符串 判断是增加页面 还是删除页面
		String uri=URIUtil.getURI(request);
		if("add".equals(uri)){
			add(request,response);
		}else if("delete".equals(uri)){
			delete(request,response);
		}
	}
	
	private void add(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
		
		String departmentCode = request.getParameter("departmentCode");
		String departmentName = request.getParameter("departmentName");
		
		
		DepartmentEntity entity = new DepartmentEntity();
		entity.setDepartmentCode(Integer.parseInt(departmentCode));
		entity.setDepartmentName(departmentName);
		
		try {
			int i=service.add(entity);
			if(i==-1){
				request.setAttribute("departmentCode", "ID重复");
				request.getRequestDispatcher("/department/fail.jsp").forward(request, response);
			}else if(i==-2){
				request.setAttribute("departmentName", "姓名重复");
				request.getRequestDispatcher("/department/fail.jsp").forward(request, response);
			}else{
				request.setAttribute("departmentCode", departmentCode);
				request.setAttribute("departmentName", departmentName);
				request.getRequestDispatcher("/department/success.jsp").forward(request, response);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	private void delete(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
		//2 拿到页面传过来的值
		String departmentCode = request.getParameter("departmentCode");
		//4把这个数据放到数据库中...
		int counter = service.delete(Integer.parseInt(departmentCode));
		String url ="";
		if(counter ==1){
			//说明成功
			url ="/department/deleteSuccess.jsp";
		}else{
			url ="/department/fail.jsp";
		}		
		request.getRequestDispatcher(url).forward(request, response);
	}
}
